<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="9">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getList">
            <el-button slot="append" icon="el-icon-search" @click="getList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>
      <template>
        <el-table :data="usersList" border stripe>
          <el-table-column type="index"></el-table-column>
          <el-table-column label="创建时间" prop="create_time">
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              <span>{{ scope.row.create_time }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username"></el-table-column>
          <el-table-column label="邮箱" prop="email"></el-table-column>
          <el-table-column label="电话" prop="mobile"></el-table-column>
          <el-table-column label="角色" prop="role_name">
            <template slot-scope="scope">
              <span>{{ scope.row.role_name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="mg_state">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
              <!-- <span>{{ scope.row.mg_state }}</span> -->
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="handleEdit(scope.$index, scope.row)"
                size="mini"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="handleDelete(scope.$index, scope.row)"
                size="mini"
              ></el-button>
              <el-tooltip
                class="item"
                effect="dark"
                content="角色分配"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                  @click="setRolePowerShow(scope.$index, scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 8, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
      <el-form ref="addDateRef" :model="addDate" label-width="70px" :rules="addDateRulse">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addDate.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addDate.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addDate.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addDate.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog title="修改用户" :visible.sync="editDialog" width="50%" @close="editDialogClosed">
      <el-form ref="editDateRef" :model="editDate" label-width="70px" :rules="addDateRulse">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editDate.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editDate.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editDate.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="EditUsers">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 角色分配 -->
    <el-dialog title="提示" :visible.sync="rolesC" width="50%" @close="InfoRoles">
      <el-form ref="rolesInfo" :v-model="userInfo">
        <el-form-item label prop="username">
          <el-input v-model="userInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="email">
          <el-input v-model="userInfo.role_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="分配角色">
          <el-select v-model="keyEd" placeholder="请选择">
            <el-option
              v-for="item in this.selectList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <!-- <el-row>
        <el-col>姓名：{{userInfo.username}}</el-col>
        <el-col style="margin-top:8px;">角色:{{userInfo.role_name}}</el-col>
        <el-col style="margin-top:8px;">
          <el-select v-model="keyEd" placeholder="请选择">
            <el-option
              v-for="item in this.selectList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesC = false">取 消</el-button>
        <el-button type="primary" @click="savaInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
   
<script>
export default {
  data() {
    var cheackEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    var cheackMobile = (rule, value, cb) => {
      const checkMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (checkMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        //当前的页数
        pagenum: 1,
        //每页显示的条数
        pagesize: 5
      },
      usersList: [],
      total: 0,
      dialogVisible: false,
      editDialog: false,
      addDate: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editDate: {},
      addDateRulse: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            min: 10,
            max: 20,
            message: '长度在 10 到 20 个字符',
            trigger: 'blur'
          },
          { validator: cheackEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            min: 11,
            max: 11,
            message: '请输入正确的手机格式',
            trigger: 'blur'
          },
          { validator: cheackMobile, trigger: 'blur' }
        ]
      },
      rolesC: false,
      userInfo: [],
      selectList: [],
      keyEd: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.$axios.get('users', { params: this.queryInfo }).then(result => {
        console.log(result.data)
        if (result.data.meta.status == 200) {
          this.usersList = result.data.data.users.reverse()
          this.total = result.data.data.total
        }
        return false
      })
    },
    handleEdit(index, row) {
      this.editDialog = true
      this.editDate = row
    },
    handleDelete(index, row) {
      console.log(row)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          //   console.log(row.id)
          this.$axios.delete('users/' + row.id).then(result => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getList()
    },
    userStateChanged(userInfo) {
      //   console.log(userInfo)
      this.$axios
        .put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
        .then(result => {
          console.log(result.data.meta.status)
          if (result.data.meta.status != 200) {
            userInfo.mg_state = !userInfo.mg_state
            this.$message({
              type: 'error',
              message: '设置用户状态失败'
            })
          } else {
            this.$message({
              type: 'success',
              message: '设置用户状态成功'
            })
          }
        })
    },
    addUser() {
      this.dialogVisible = true
    },
    addDialogClosed() {
      this.$refs.addDateRef.resetFields()
    },
    editDialogClosed() {
      this.$refs.editDateRef.resetFields()
    },
    addUsers() {
      this.$refs.addDateRef.validate(valid => {
        if (valid) {
          //   alert('submit!')
          this.$axios.post('users', this.addDate).then(result => {
            console.log(result)
            this.$message({
              type: 'success',
              message: result.data.meta.msg
            })
            this.dialogVisible = false
            this.getList()
          })
        } else {
          this.$message({
            type: 'error',
            message: '添加失败'
          })
          this.dialogVisible = false
          return false
        }
      })
    },
    EditUsers() {
      this.$refs.editDateRef.validate(valid => {
        if (valid) {
          //   alert('submit!')
          this.$axios
            .put('users/' + this.editDate.id, {
              email: this.editDate.email,
              mobile: this.editDate.mobile
            })
            .then(result => {
              this.$message({
                type: 'success',
                message: result.data.meta.msg
              })
              this.editDialog = false
              this.getList()
            })
        } else {
          this.$message({
            type: 'success',
            message: '跟新失败'
          })
          return false
        }
      })
    },
    setRolePowerShow(index, row) {
      this.$axios.get('roles').then(result => {
        this.selectList = result.data.data
      })
      this.userInfo = row
      this.rolesC = true
    },
    savaInfo() {
      if (!this.keyEd) {
        this.$message({
          type: 'warning',
          message: '请分配职务'
        })
      } else {
        this.$axios
          .put(`users/${this.userInfo.id}/role`, { rid: this.keyEd })
          .then(result => {
            this.$message({
              type: 'success',
              message: result.data.meta.msg
            })
            this.rolesC = false
            this.getList()
          })
      }
    },
    InfoRoles() {
      this.userInfo = []
      this.keyEd = ''
    }
  }
}
</script>
<style scoped>
</style>